#include <time.h>
#include <mysql/mysql.h>
#include <string.h>
#include "shtml.h"
#include <stdarg.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <signal.h>
#include <errno.h>

#define BUFFER_SIZE 1024
static char host_name[BUFFER_SIZE];
static char user_name[BUFFER_SIZE];
static char password [BUFFER_SIZE];
static char db_name  [BUFFER_SIZE];

static int port_number;
static bool DEBUG=false;

#define LOCKFILE "/var/run/giavang.pid"
#define LOCKMODE (S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH)
static MYSQL *conn;



//Doc file cau hinh
int after_equal(char * c){
	int i=0;
	for(;c[i]!='\0'&&c[i]!='=';i++);
	return ++i;
}
void trim(char * c)
{
    char buf[BUFFER_SIZE];
    char * start,*end;
    strcpy(buf,c);
    start=buf;
    while(isspace(*start)) start++;
    end=start;
    while(!isspace(*end)) end++;
    *end='\0';
    strcpy(c,start);
}
bool read_buf(char * buf,const char * key,char * value)
{
   if (strncmp(buf,key, strlen(key)) == 0)
    {
		strcpy(value, buf + after_equal(buf));
		trim(value);
		return 1;
   }
   return 0;
}
void read_int(char * buf,const char * key,int * value)
{
	char buf2[BUFFER_SIZE];
	if (read_buf(buf,key,buf2))
		sscanf(buf2, "%d", value);

}
void write_log(const char *fmt, ...)
{
	va_list         ap;
	char            buffer[4096];
	char times[20];
    struct tm *sTm;
    time_t now = time (0);
    sTm = gmtime (&now);
    strftime (times, sizeof(times), "%Y-%m-%d %H:%M:%S", sTm);

	sprintf(buffer,"/var/log/baogia.log");
	FILE *fp = fopen(buffer, "a+");
	if (fp==NULL)
    {
		 fprintf(stderr,"openfile error!\n");
		 system("pwd");
	}va_start(ap, fmt);
	vsprintf(buffer, fmt, ap);
	fprintf(fp,"%s \t %s\n",times,buffer);
	//if (DEBUG) printf("%s\n",buffer);
	va_end(ap);
	fclose(fp);

}

//Khoi tao mysql
bool init_mysql_conf()
{
	FILE *fp=NULL;
	char buf[BUFFER_SIZE];
	host_name[0]=0;
	user_name[0]=0;
	password[0]=0;
	db_name[0]=0;
	port_number=3306;

	fp = fopen("/etc/baogia.conf", "r");
	if(fp!=NULL)
    {
        while (fgets(buf, BUFFER_SIZE - 1, fp))
        {
            read_buf(buf,"F_HOST_NAME",host_name);
            read_buf(buf, "F_USER_NAME",user_name);
            read_buf(buf, "F_PASSWORD",password);
            read_buf(buf, "F_DB_NAME",db_name);
            read_int(buf , "F_PORT_NUMBER", &port_number);

        }
        write_log("Load file %s %s %s %s",host_name,user_name,password,db_name);
		return true;
	//	fclose(fp);
    }
    else
    {
        write_log("Cannot open file 'baogia.conf'");
        return false;
    }
}
bool executesql(const char * sql)
{
	if (mysql_real_query(conn,sql,strlen(sql)))
    {
		write_log("Error in sql %s:%s",sql,mysql_error(conn));
		sleep(20);
		conn=NULL;
		return false;
	}
	else
	    return true;
}

bool init_mysql() {
    if(conn==NULL)
    {
		conn=mysql_init(NULL);		// init the database connection
		/* connect the database */
		const char timeout=30;
		mysql_options(conn,MYSQL_OPT_CONNECT_TIMEOUT,&timeout);

		if(!mysql_real_connect(conn,host_name,user_name,password,db_name,port_number,0,0))
        {
			write_log("Error init mysql with host=%s,user=%s,pass=%s,db=%s: %s",host_name,user_name,password,db_name,mysql_error(conn));
			sleep(20);
			return false;
		}
	}
	if (!executesql("set names utf8"))
    {
        return false;
    }

	return true;
}
//Xu li chinh


int post_blog()
{
    char cmd[200];
    FILE *stream;
    int MAX_BUFFER = 1000;
    int p_id=0;
    char buffer[MAX_BUFFER];
    sprintf(cmd,"wget -q -O - http://baogia.info/postblog.php");
    //system(cmd);
    stream = popen(cmd, "r");
    if ( fgets(buffer, MAX_BUFFER, stream) != NULL )
    {
        if (strlen(buffer)>1)
        {
            char sql[500];
            sprintf(sql,"update wp_posts set  post_status = 'publish' where ID=%s",buffer);
            if (DEBUG)
                cout<<sql<<endl;
            else
                executesql(sql);
            write_log("Add blog entry %s",buffer);
            p_id = atoi(buffer);
        }
        //break;
    }
    pclose(stream);
    return p_id;
}
void postfb(int p_id)
{
    char cmd[500];
    char a_t[500];
    char p_i[]="179405695564178";
    FILE *stream;
    stream = popen("http://baogia.info/getoption.php?key=fb-page-act", "r");
    fgets(a_t, 500, stream);
    pclose(stream);
    //char lnk[]="http://baogia.info/bao-gia-vang/";
    sprintf(cmd,"curl -X POST -F 'message=Gia vang ' -F 'link=http://baogia.info/?p=%d' -F 'access_token=%s' https://graph.facebook.com/%s/feed",p_id,a_t,p_i);
    system(cmd);
}
int main(int argc, char** argv)
{
    init_mysql_conf();
    init_mysql();
    if (argc>1) DEBUG=true;
    int p=post_blog();
    postfb(p);
    return 0;
}
